/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kedacom.demo.jmx.action;

import java.io.FileOutputStream;
import java.io.PrintWriter;
import javax.management.MBeanServer;
import javax.management.ObjectName;

/**
 *
 * @author Administrator
 */
public class Logger implements LoggerMBean, MBeanRegistration {

    public static final int ALL = 3;
    public static final int ERRORS = 2;
    public static final int NONE = 1;
    private PrintWriter out = null;
    private int logLevel = Logger.ALL;
    private MBeanServer server = null;

    public Logger() {

        try {

            //open the initial log file

            PrintWriter out = new PrintWriter(
                    new FileOutputStream("record.log "));

        }
        catch (Exception e) {

            e.printStackTrace();

        }

    }

    @Override
    public void setLogLevel(int level) {

        logLevel = level;

    }

    @Override
    public int getLogLevel() {

        return logLevel;

    }

    @Override
    public String retrieveLog(int linesback) {

        //implementation here

        return null;

    }

    @Override
    public void writeLog(String message, int type) {

        try {

            if (type <= logLevel) {
                out.println(message);
            }

        }
        catch (Exception e) {

            e.printStackTrace();

        }
    }

    @Override
    public void postDeregister() {
    }

    @Override
    public void postRegister(Boolean registrationDone) {
    }

    @Override
    public void preDeregister() {
    }

    @Override
    public ObjectName preRegister(
            MBeanServer server, ObjectName name) {

        this.server = server;

        try {

            ObjectName name1 = new ObjectName(
                    "HelloAgent:name=props");

            Object[] params = {"loglevel"};

            String[] sig = {"java.lang.String"};

            String value = (String) server.invoke(name1, "getProperty", params, sig);

            logLevel =
                    Integer.parseInt(value);

        }
        catch (Exception e) {

            e.printStackTrace();

            logLevel = 0;

        }

        return name;

    }
}
